﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BitOperations
{
    /* Problem description
     * 
     * Find out the number of ones in an integer
     * 
     */
 
    class NumberOfOnes
    {
        public int GetOneNumbers(int num, int version)
        {
            int count = 0;

            // version 1: stupid shifting one bit by one bit
            if (version == 1)
            {
				uint x = (uint)num; // use unsigned int to cover negative integers
                while (x > 0)
                {
                    if((x & 1) == 1) ++count;
                    x >>= 1;
                }
            }
            else // version 2: faster
            {
                while (num != 0)
                {
                    num &= (num - 1);
                    ++count;
                }
            }

            return count;
        }



        static void Main(string[] args)
        {
            NumberOfOnes noo = new NumberOfOnes();
            int number = -5; // 1111 1111 1111 1111 1111 1111 1111 1011

            Console.WriteLine("Integer is {0}, number of ones of it is {1}", number, noo.GetOneNumbers(number, 2));

            Console.WriteLine("Press any key to finish...");
            Console.ReadKey();
        }
    }
}